package code.D1214;

import java.time.Period;
import java.util.HashMap;
import java.util.Map;

/**
 * author : yeswater
 * date : 2023/12/14
 * <p>
 * 从前序与中序遍历构造二叉树 mid
 * 
 * 代码随想录思路
 */

public class T105 {
    // 存储 inorder<val, index>
    HashMap<Integer, Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        
        int n = inorder.length;
        for (int i = 0; i < n; i++) {
            map.put(inorder[i], i);
        }
        
        return dfs(preorder, 0, n - 1, inorder, 0, n - 1);
    }
    
    private TreeNode dfs(int[] preorder, int ps, int pe, int[] inorder, int is, int ie) {
        // base case
        if (ps > pe) return null;
        
        // Build Tree with preorder. 先序的第一个值就是 root.val
        TreeNode root = new TreeNode(preorder[ps]);
        
        // find inorder root 
        int rootIdx = map.get(root.val);
        
        int diff = rootIdx - is;
        
        root.left = dfs(preorder, ps + 1, ps + diff, inorder, is, rootIdx - 1);
        root.right = dfs(preorder, ps + diff + 1, pe, inorder, rootIdx + 1, ie);
        return root;
    }
    
    
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        
        TreeNode() {
        }
        
        TreeNode(int val) {
            this.val = val;
        }
        
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
